<?php
/**
 * 常用函数扩展类
 */
class ext_fun {

    //加密 $RAW为0时兼容ios客户端
    function toacii($str,$key = "6123567464806ad23e6a9e74adddab82",$RAW = OPENSSL_RAW_DATA){
        $str = (is_object($str) || is_array($str)) ? json_encode($str) : $str;
        $data = base64_encode(openssl_encrypt($str,'AES-128-CBC',substr(md5($key),8,16),$RAW,'1234567890123456'));
        return str_replace(array('+','/','='),array('-','_','*'),$data);
    }

    //解密 $RAW为0时兼容ios客户端
    function tostring($str,$key = "6123567464806ad23e6a9e74adddab82",$RAW = OPENSSL_RAW_DATA){
        $str = str_replace(array('-','_','*'),array('+','/','='),$str);
        $data = openssl_decrypt(base64_decode($str),'AES-128-CBC',substr(md5($key),8,16),$RAW,'1234567890123456');
        return (null === json_decode($data, true)) ? $data : json_decode($data, true);
    }

    //将post数据解密
    function depost($post){
        $post = $this->tostring($post);
        $post = $this->convertUrlArray($post);
        return $post;
    }

    //url转数组
    function convertUrlArray($query){
        $queryParts = explode('&', $query);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }
   
    /**
     * 验证邮箱地址格式
     */
    function isEmail($email){
        if (preg_match("/[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-z]{2,4}/",$email,$mail))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 验证用户名是否以字母开头
     */
    function isUserNum($user){
        if (preg_match("/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){3,19}$/",$user,$username))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 验证密码只能为数字和字母的组合
     */
    function isPsd($psd){
        if (preg_match("/^(\w){4,20}$/",$psd,$password))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    /**
     * 转跳到url
     */
    function salt($length){
        $key = md5(rand(11111111,99999999));
        $key = substr($key, 0,$length);
        return $key;
    }

    /**
     * 获取用户真实IP
     */
    function getIP(){
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
            if ($_SERVER["HTTP_CLIENT_IP"]){
                $proxy = addslashes($_SERVER["HTTP_CLIENT_IP"]);
            }
            else{
                $proxy = addslashes($_SERVER["REMOTE_ADDR"]);
            }
            $ip = addslashes($_SERVER["HTTP_X_FORWARDED_FOR"]);
        }else{
            if (isset($_SERVER["HTTP_CLIENT_IP"])){
                $ip = addslashes($_SERVER["HTTP_CLIENT_IP"]);
            }else{
                $ip = addslashes($_SERVER["REMOTE_ADDR"]);
            }
        }
        $ip = addslashes($ip);
        if (strpos($ip, ", ")!==false) $ip = end(explode(", ", $ip));
        return $ip;
    }

    /**
     * 字符串截取
     */
    function strSub($string, $sublen, $start){
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);

        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen));
        return join('', array_slice($t_string[0], $start, $sublen));
    }

    /**
     * 首尾截取字符串
     */
    function strCut($string,$strstart,$strend){
        $v_a=explode($strstart, $string);
        $v_a=explode($strend, $v_a[1]);
        return $v_a[0];
    }

    /**
     * 字符串替换
     */
    function strReplace($str){
        $str=str_replace("<","&lt;",$str);
        $str=str_replace(">","&gt;",$str);
        $str=str_replace("object","",$str);
        $str=str_replace("script","",$str);

        return $str;
    }

    /**
     * 转义提交数据中的HTML代码
     */
    function clearHTML($val){
        return ltrim(chop(htmlspecialchars($val)));
    }

    /**
     * 清空字符串中的HTML标签
     */
    function clearLabel($html){
        $search = array ("'<script[^>]*?>.*?</script>'si", "'<[/!]*?[^<>]*?>'si", "'([rn])[s]+'", "'&(quot|#34);'i", "'&(amp|#38);'i", "'&(lt|#60);'i", "'&(gt|#62);'i", "'&(nbsp|#160);'i", "'&(iexcl|#161);'i", "'&(cent|#162);'i", "'&(pound|#163);'i", "'&(copy|#169);'i", "'&#(d+);'e");
        $replace = array ("", "", "\1", "\"", "&", "<", ">", " ", chr(161), chr(162), chr(163), chr(169), "chr(\1)");

        return @preg_replace($search, $replace, $html);
    }

    /**
    * 创建多级目录
    */
    function createDir($dir){
        if(!is_dir($dir)){
            if(!createDir(dirname($dir))){
                return false;
            }
            if(!mkdir($dir,0777)){
                return false;
            }
        }
        return true;
    }
    
    // 一次只能创建一级目录,成功返回1
    function createDir0($dirname,$mode=0777){
        if(is_null($dirname) || $dirname=="")   return false;
        if(!is_dir($dirname)){
            return mkdir($dirname,$mode);
        }
    }

    //检查目录或文件是否存在
    function isExists($filename1 = ''){
        if(file_exists($filename1)) return true;
        return false;
    }
    
    //删除目录包括有文件 
    function delDir($dirname){
        if($this->isExists($dirname) and is_dir($dirname))
        {
            if(!$dirhandle=opendir($dirname)) return false;
            while(($file=readdir($dirhandle))!==false)
            {
                if($file=="." or $file=="..")   continue;
                $file=$dirname.DIRECTORY_SEPARATOR.$file;  //表示$file是$dir的子目录
                if(is_dir($file))
                {
                    delDir($file);
                }
                else
                {
                    unlink($file);
                }
            }
            closedir($dirhandle);
            return rmdir($dirname);
        }
        return false;
    }

    //复制文件
    function copyFile($srcfile,$newfile){
        if(is_file($srcfile)){
            if(!file_exists($newfile))
            return copy($srcfile,$newfile);
        }
        return false;
    }

    //删除文件
    function delFile($filename){
        if($this->isExists($filename) and is_file($filename)) return unlink($filename);
        return false;
    }

    //将字符串写入文件
    function writeStr($filename,$str){
        if(function_exists(file_put_contents)){
            file_put_contents($filename,$str);
        }else{
            $fp=fopen($filename,"wb");
            fwrite($fp,$str);
            fclose($fp);
        }
    }

    function get_http_type(){
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        return $http_type;
    }
}       
?>